package com.tianji.promotion.service.impl;

import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.utils.StringUtils;
import com.tianji.promotion.enums.ExchangeCodeStatus;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.tianji.common.utils.CollUtils;
import com.tianji.promotion.constants.PromotionConstants;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author 林云
 * @since 2023-08-22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    private final StringRedisTemplate redisTemplate;

    /**
     * 生成兑换码
     */
    @Override
    @Async("generateExchangeCodeExecutor")
    public void asyncGenerateExchangeCode(Coupon coupon) {
        log.debug("生成兑换码---线程名---{}", Thread.currentThread().getName());
        // 1.生成自增id
        Integer totalNum = coupon.getTotalNum();
        // 2.一次性自增，不用循环调用redis
        Long increment = redisTemplate.opsForValue().increment(PromotionConstants.COUPON_CODE_SERIAL_KEY, totalNum);
        if (increment == null) {
            return;
        }
        // 3.量生成兑换码
        int maxSerialNum = increment.intValue();
        int begin = maxSerialNum - totalNum + 1;// 从上一次+1开始
        List<ExchangeCode> list = new ArrayList<>();
        for (int serialNum = begin; serialNum <= maxSerialNum; serialNum++) {
            ExchangeCode exchangeCode = new ExchangeCode();
            String code = CodeUtil.generateCode(serialNum, coupon.getId());
            exchangeCode.setId(serialNum);
            exchangeCode.setCode(code);
            exchangeCode.setExpiredTime(coupon.getIssueEndTime());
            exchangeCode.setExchangeTargetId(coupon.getId());
            list.add(exchangeCode);
        }
        // 4.批量保存
        this.saveBatch(list);
        // 5.写入redis中
        redisTemplate.opsForZSet().add(PromotionConstants.COUPON_RANGE_KEY, coupon.getId().toString(), maxSerialNum);
    }

    /**
     * 检查兑换码是否已兑换
     */
    @Override
    public boolean updateExchangeCodeMark(Long serialNum, Boolean flag) {
        String key = PromotionConstants.COUPON_CODE_MAP_KEY;
        //返回true表示已存在
        Boolean oldValue = redisTemplate.opsForValue().setBit(key, serialNum, flag);
        return oldValue != null && oldValue;
    }


}
